package com.lambkit.core.http;

import com.lambkit.core.exception.LambkitRenderException;
import com.lambkit.core.json.Json;

import java.nio.charset.StandardCharsets;

/**
 * @author yangyong(孤竹行)
 */
public class JsonRender implements IRender {
    protected boolean forIE = false;
    private String jsonText;

    public JsonRender() {
    }

    public JsonRender(String jsonText) {
        if (jsonText == null) {
            this.jsonText = "null";
        } else {
            this.jsonText = jsonText;
        }
    }

    public JsonRender(Object data) {
        this.jsonText = Json.use().toJson(data);
    }

    public JsonRender forIE() {
        this.forIE = true;
        return this;
    }

    @Override
    public void render(IHttpContext context) {
        if (this.jsonText == null) {
            this.jsonText = Json.use().toJson(context.getRequestAttrs(null));
        }
        try {
            String contentType = this.forIE ? "text/html" : "application/json";
            //contentType = contentType + ";charset=" + response.getCharacterEncoding();
            context.getResponse().setContentType(contentType);
            context.getResponse().write(this.jsonText.getBytes(StandardCharsets.UTF_8));
            context.getResponse().close();
        } catch (Exception exception) {
            throw new LambkitRenderException(exception);
        }
    }
}
